package com.chen.springboot.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chen.springboot.common.AuthAccess;
import com.chen.springboot.common.Result;
import com.chen.springboot.dto.UserDto;
import com.chen.springboot.entity.User;
import com.chen.springboot.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 还有这里的@RestController因为是前后端分离项目，所以后端只用返回json数据就可以了，或者说对象数据。
 * 所以不能用@Controller，它会返回一个视图
 */
@Api(tags = {"用户接口"})
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @ApiOperation("用户注册")
    @AuthAccess(message = "注册页面放行")
    @PostMapping("/register")
    public Result<?> register(@RequestBody User user) {
        userService.register(user);
        return Result.success();
    }

    @ApiOperation("用户登录")
    @PostMapping("/login")
    public Result<?> login(@RequestBody User user) {
        UserDto userDto = userService.login(user);
        return Result.success(userDto);
    }

    @ApiOperation("管理员登录")
    @PostMapping("/manageLogin")
    public Result<?> manageLogin(@RequestBody User user) {
        UserDto userDto = userService.manageLogin(user);
        return Result.success(userDto);
    }

    @ApiOperation("新增用户")
    @PostMapping
    public Result<?> save(@RequestBody User user) {
        userService.save(user);
        return Result.success();
    }

    @ApiOperation("更新用户信息")
    @PutMapping
    public Result<?> update(@RequestBody User user) {
        userService.update(user);
        return Result.success();
    }

    @ApiOperation("删除用户")
    @DeleteMapping
    public Result<?> delete(@RequestParam Long id) {
        userService.delete(id);
        return Result.success();
    }

    @ApiOperation("获取所有用户")
    @GetMapping
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String search) {
        Page<User> userPage = userService.findPage(pageNum, pageSize, search);
        return Result.success(userPage);
    }
}